package com.seawave.sdkclientjdk11.service;

import com.google.gson.Gson;
import com.seawave.sdkclientjdk11.util.HttpUtil;
import com.seawave.sdkclientjdk11.vo.enums.HttpMethod;
import com.seawave.sdkcore.Des3Util;
import com.seawave.sdkcore.Md5Util;
import com.seawave.sdkcore.RsaUtil;
import com.seawave.sdkcore.vo.base.BaseRequest;
import com.seawave.sdkcore.vo.base.BaseResponse;
import com.seawave.sdkcore.vo.iot.IotRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.ParameterizedType;
import java.util.UUID;

/**
 * @ClassName AbstractService
 * @Description: 物联卡业务接口抽象类
 * @Author: Jing GuangYong
 * @Date: 2020/2/6 20:07
 * @Version: 1.0
 */
public abstract class AbstractService <Request extends BaseRequest, Response extends BaseResponse> implements IService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractService.class);
    /**
     * 通过反射获取model的真实类型
     */
    Class<Request> requestClazz = (Class<Request>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    Class<Response> responseClazz = (Class<Response>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];

    private final Gson gson = new Gson();

    /**
     * 返回接口地址
     * @return
     */
    protected abstract String getInterfaceUrl(BaseRequest request);

    /**
     * 请求接口
     * @param iotRequest
     * @param request
     * @return
     */
    public BaseResponse call(final IotRequest iotRequest, BaseRequest request) {
        String requestMessage = iotRequest.getRequestMessage();
        final String url = this.getInterfaceUrl(request);
        LOGGER.debug("请求url： " + url);
        LOGGER.debug("请求报文： \n" + requestMessage);
        String jsonString= HttpUtil.postJson(url, HttpMethod.POST, requestMessage);
        LOGGER.debug("响应报文： \n" + jsonString);
        Response result  = gson.fromJson(jsonString, responseClazz);
        return result;
    }

    /**
    * @Description: 参数加密
    * @Author: Jing GuangYong
    * @Date: 2020/2/6 20:09
    * @Param
    * @return
    */
    protected IotRequest encryptMsg(final BaseRequest request) throws Exception {
        String uuid= UUID.randomUUID().toString();
        String appId= request.getAppid();
        LOGGER.debug("appId=====" + appId);
        String appKey= RsaUtil.encrypt(uuid, request.getPublicKey());
        LOGGER.debug("appKey=====" + appKey);
        String bizJson = this.gson.toJson(request);
        String param= Des3Util.encrypt(bizJson, uuid);
        LOGGER.debug("param=====" + param);
        String sign= Md5Util.getSign(param, uuid);
        LOGGER.debug("sign=====" + sign);
        return new IotRequest(appId,appKey, param, sign );
    }
}